package com.xinyue.ext.reader.bean;

import org.dom4j.Element;

import com.xinyue.ext.Label;
import com.xinyue.ext.exception.BeanException;
import com.xinyue.ext.reader.ParamHolder;
import com.xinyue.ext.util.ListWrapper;
import com.xinyue.ext.util.StringUtil;

/**
 * 读取XML文件中的entity标签中的bean信息并返回封装对象
 */
public class BeanReader implements Label {
	//参数集
	private static ParamHolder holder;
	
	//私有构造器
	private BeanReader() {
	}
	//内部类
	private static class SingletonHolder{
        private static BeanReader instance = new BeanReader();  
    }
	/**
	 * 获得对象实例
	 */
	public static BeanReader getInstance(ParamHolder holder) {
		BeanReader.holder = holder;
		//bean对象的import文件路径集合
		BeanReader.holder.setBeanImpt(new ListWrapper());
		return SingletonHolder.instance;
	}
	
	/**
	 * 读取property信息并封装至BeanData对象
	 * 此方法传入entity标签，仅读取id及property标签，通过遍历匹配封装至BeanData对象
	 */
	public void read(Element entity) throws Exception {
		String className = entity.attributeValue(name_);
		String table = entity.attributeValue(table_);
		if(StringUtil.isNull(className)) {
			throw new BeanException("未定义name属性或name属性为空", holder.getException());
		}
		//异常配置信息
		holder.getException().setEntityName(className);
		
		//当table为空时，默认表名和Entity同名
		if(StringUtil.isNull(table)) {
			holder.getEntity().setTable(className.toUpperCase());
		}else {
			holder.getEntity().setTable(table);
		}
		holder.getEntity().setClassName(className);
		
		//id标签
		IdProcess.getInstance(holder).read(entity);
		//property标签
		PropertyProcess.getInstance(holder).read(entity);
		//order-by标签
		OrderProcess.getInstance(holder).read(entity);
		//many和one标签
		RelyProcess.getInstance(holder).read(entity);
		
		//set import
		holder.getEntity().setImports(holder.getBeanImpt().getList());
	}
}